// 推荐用户管理的函数

var constant = require('../../const');
var models = require('../../models');
var chat = require('../../common/chat');
var fs = require('fs');
var AV = require('leanengine')


/*
 * title: 获取口袋恋人管理的页面
 */
function getPocketUser(req, res) {
		if (!req.AV.user) {
			res.redirect('/admin');
		}
		var status = req.query.status || 0;
		var query = new AV.Query(models.MPUser);
		//query.equalTo("type",1);

		query.skip(status);
		query.descending("createdAt");

		query.find({
			success: function(users) {
				var data = {
					"username": req.session.username,
					"avatar": req.session.useravatar,
					"users": users
				};
				res.render('admin/pocketUser', data);
			},
			error: function(error) {
				console.log(error)
//				res.render('admin/pocketUser', {
//					"username": req.session.username,
//					"avatar": req.session.useravatar
//				});
			}
		});
	}
	/*
	 * title: 获取推荐用户管理的页面
	 */

function getUser(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var status = req.query.status || 0;
	var query = new AV.Query(models.MLUser);
	query.equalTo("type", 2);

	query.include("belongToArticle");
	query.limit(1000);
	query.skip(status);
	query.descending("createdAt");
	query.find({
		success: function(users) {
			var data = {
				"username": req.session.username,
				"users": users
			};
			res.render('admin/recommendUser/index', data);
		},
		error: function(error) {
			res.render('admin/recommendUser/index', {
				"username": req.session.username
			});
		}
	});
}

/*
 * title: 获取新增用户页面
 */
function getUserAdd(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	res.render('admin/recommendUser/add', {
		"username": req.session.username
	});
}

/*
 * title: 保存新建的推荐用户
 */
function userAdd(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var userId = req.body.userId;
	var query = new AV.Query(models.MLUser);
	query.get(userId, {
		success: function(user) {
			user.set("type", constant.USER_TYPE_PROFESSIONAL);
			user.set('price', 0.5);
			user.save().then(function(user) {
				var tokenQuery = new AV.Query(models.HXToken);
				tokenQuery.descending("createdAt");
				tokenQuery.find({
					success: function(results) {
						var token = results[0].get('token');
						// 发送会话消息
						AV.Cloud.httpRequest({
							method: 'POST',
							url: 'https://a1.easemob.com/xiaocan/' + constant.APP_NAME + '/messages',
							headers: {
								"Content-Type": "application/json",
								"Authorization": "Bearer " + token
							},
							body: {
								"target_type": "users", // users 给用户发消息, chatgroups 给群发消息
								"target": [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
								// 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
								// 数组元素是groupid
								"msg": {
									"type": "cmd",
									"action": constant.ACTION_AUTHENTICATE_SUCCEED
								},
								"from": "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
							},
							success: function(httpResponse) {
								AV.Cloud.run('sendSysMsg', {
									"touserId": user.id,
									"msg": "亲爱的" + user.get("nickname") + "，你的口袋恋人申请已经通过，你现在已经是一名正式的口袋恋人了。用心聆听，发现别人的故事，遇见更美的自己。如果想被更多人看到，可以写出你的故事，被推荐上主页，原位置就可以申请哦"
								}, {
									success: function(result) {
										res.send({
											"code": 0,
											"msg": "成功"
										});
									},
									error: function(error) {
										res.send({
											"code": 1,
											"msg": "发送失败"
										});
									}
								});
								//将原有的恋人分手
								var sweetheartQuery1 = new AV.Query(models.MLSweetheart);
								sweetheartQuery1.equalTo("sponsor", user);
								var sweetheartQuery2 = new AV.Query(models.MLSweetheart);
								sweetheartQuery2.equalTo("winner", user);
								var mainQuery = AV.Query.or(sweetheartQuery1, sweetheartQuery2);
								mainQuery.find({
									success: function(sweets) {
										if (sweets.length == 0) {
											return;
										}
										for (i = 0; i < sweets.length; i++) {
											sweets[i].set("status", 0);
											sweets[i].save().then(function(sweet) {
												if (sweet.get("sponsor").id == user.id) {
													AV.Cloud.run("sendSweetApplyCMDMsg", {
														"touserId": sweet.get("winner").id,
														"fromuserId": user.id,
														"nick": user.get("nickname"),
														"actions": constant.ACTION_SWEET_DELETE
													}, null);
												} else {
													AV.Cloud.run("sendSweetApplyCMDMsg", {
														"touserId": sweet.get("sponsor").id,
														"fromuserId": user.id,
														"nick": user.get("nickname"),
														"actions": constant.ACTION_SWEET_DELETE
													}, null);
												}
											})
										}
									},
									error: function() {

									}
								});
							},
							error: function(httpResponse) {
								res.send({
									"code": 1,
									"msg": "发送失败"
								});
							}
						});
					},
					error: function(error) {
						res.send({
							"code": 1,
							"msg": "请求失败"
						});
					}
				})
			})
		},
		error: function(error) {
			res.redirect("/admin/recommendUser/add");
		}
	});
}


/*
 * title: 获取用户编辑页面
 */
function getUserEdit(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var objectId = req.query.objectId;

	var articleQuery = new AV.Query(models.MLArticle);
	articleQuery.equalTo("status", constant.article_STATUS_EDITING);
	articleQuery.find({
		success: function(articles) {
			// 编辑文章
			var recommendUserQuery = new AV.Query(models.MLRecommendUser);
			recommendUserQuery.include("article");
			recommendUserQuery.include("user");
			recommendUserQuery.get(objectId, {
				success: function(recommendUser) {
					var data = {
						"username": req.session.username,
						"articles": articles,
						"recommendUser": recommendUser
					};
					res.render('admin/recommendUser/edit', data);
				},
				error: function(error) {
					res.redirect("/admin/recommendUser");
				}
			});
		},
		error: function(error) {
			res.redirect("/admin/recommendUser");
		}
	});
}

/*
 * title: 保存文章的修改
 */
function userEdit(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var title = req.body.title;
	var desc = req.body.desc;
	var recommendUserImg = req.files.recommendUserImg;
	var topicId = req.body.topicId;
	var objectId = req.body.objectId;

	// 编辑文章
	var recommendUserQuery = new AV.Query(models.MLArticle);
	recommendUserQuery.get(objectId).then(function(recommendUser) {
		// 如果有新的照片
		if (recommendUserImg.name) {
			// 上传照片
			fs.readFile(recommendUserImg.path, function(err, imgData) {
				if (err) {
					res.redirect('admin/recommendUser');
				} else {
					// 保存图片
					var avFile = new AV.File(recommendUserImg.name, imgData);
					avFile.save().then(function() {
						// 文件保存成功, 修改专题
						recommendUser.set("title", title);
						recommendUser.set("title_img", avFile);
						recommendUser.set("desc", desc);
						if (topicId) {
							var topic = new models.MLTopic;
							topic.id = topicId;
							recommendUser.set("topic", topic);
						} else {
							recommendUser.set("topic", null);
						}
						recommendUser.save({
							success: function() {
								res.redirect('admin/recommendUser');
							},
							error: function(error) {
								res.redirect('admin/recommendUser');
							}
						});

					}, function(error) {
						res.redirect('admin/recommendUser');
					});
				}
			});

		} else {
			// 只保存非图片信息
			recommendUser.set("title", title);
			recommendUser.set("desc", desc);
			if (topicId) {
				var topic = new models.MLTopic;
				topic.id = topicId;
				recommendUser.set("topic", topic);
			} else {
				recommendUser.set("topic", null);
			}
			recommendUser.save({
				success: function() {
					res.redirect('admin/recommendUser');
				},
				error: function(error) {
					res.redirect('admin/recommendUser');
				}
			});
		}

	}, function(error) {
		res.redirect('admin/recommendUser');
	});
}


/*
 * title: 删除该编辑推荐
 */
function deleteRecmmandUser(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var objectId = req.body.objectId;
	// 编辑专题
	var recommendUserQuery = new AV.Query(models.MLUser);
	recommendUserQuery.get(objectId, {
		success: function(user) {
			user.set("type", constant.USER_TYPE_NORMAL);
			user.set('price', 0.5);
			user.save().then(function(user) {
				var tokenQuery = new AV.Query(models.HXToken);
				tokenQuery.descending("createdAt");

				tokenQuery.find({
					success: function(results) {
						var token = results[0].get('token');
						// 发送会话消息
						AV.Cloud.httpRequest({
							method: 'POST',
							url: 'https://a1.easemob.com/xiaocan/' + constant.APP_NAME + '/messages',
							headers: {
								"Content-Type": "application/json",
								"Authorization": "Bearer " + token
							},
							body: {
								"target_type": "users", // users 给用户发消息, chatgroups 给群发消息
								"target": [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
								// 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
								// 数组元素是groupid
								"msg": {
									"type": "cmd",
									"action": constant.ACTION_RESET_USER
								},
								"from": "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
							},
							success: function(httpResponse) {
								AV.Cloud.run('sendSysMsg', {
									"touserId": user.id,
									"msg": "亲爱的" + user.get("nickname") + "，因为不符合规定，你的身份将被设置为实习恋人。请重新申请成为口袋恋人。如果有问题，请和口袋君交流哦。"
								}, {
									success: function(result) {
										res.send({
											"code": 0,
											"msg": "发送成功"
										});
									},
									error: function(error) {
										res.send({
											"code": 1,
											"msg": "发送失败"
										});
									}
								});
								//将原有order 写空
								var sweetheartQuery1 = new AV.Query(models.MLSweetheart);
								sweetheartQuery1.equalTo("sponsor", user);
								var sweetheartQuery2 = new AV.Query(models.MLSweetheart);
								sweetheartQuery2.equalTo("winner", user);
								var mainQuery = AV.Query.or(sweetheartQuery1, sweetheartQuery2);
								mainQuery.find({
									success: function(sweets) {
										if (sweets.length == 0) {
											return;
										}
										for (i = 0; i < sweets.length; i++) {
											sweets[i].set("belongOrder", null);
											sweets[i].save();
										}
									},
									error: function() {

									}
								});
							},
							error: function(httpResponse) {
								res.send({
									"code": 1,
									"msg": "发送失败"
								});
							}
						});
					},
					error: function(error) {
						res.send({
							"code": 1,
							"msg": "请求失败"
						});
					}
				})
			});
		},
		error: function(error) {
			res.send({
				"code": 1,
				"msg": "失败"
			});
		}
	});
}

/*
 * 设置成为编辑推荐
 */
function setEdit(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var objectId = req.body.objectId;
	var recommendUserQuery = new AV.Query(models.MLUser);
	recommendUserQuery.get(objectId, {
		success: function(user) {
			user.set("type", constant.USER_TYPE_EDIT);
			user.save().then(function(user) {
				var tokenQuery = new AV.Query(models.HXToken);
				tokenQuery.descending("createdAt");

				tokenQuery.find({
					success: function(results) {
						var token = results[0].get('token');
						// 发送会话消息
						AV.Cloud.httpRequest({
							method: 'POST',
							url: 'https://a1.easemob.com/xiaocan/' + constant.APP_NAME + '/messages',
							headers: {
								"Content-Type": "application/json",
								"Authorization": "Bearer " + token
							},
							body: {
								"target_type": "users", // users 给用户发消息, chatgroups 给群发消息
								"target": [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
								// 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
								// 数组元素是groupid
								"msg": {
									"type": "cmd",
									"action": constant.ACTION_RESET_USER
								},
								"from": "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
							},
							success: function(httpResponse) {
								AV.Cloud.run('sendSysMsg', {
									"touserId": user.id,
									"msg": "亲爱的" + user.get("nickname") + "，你的故事让小编印象深刻，相信可以感染到更多人。你现在可是一名编辑推荐的优秀口袋恋人了哟～你的故事近期将在恋人故事版块出现"
								}, {
									success: function(result) {
										res.send({
											"code": 0,
											"msg": "发送成功"
										});
									},
									error: function(error) {
										res.send({
											"code": 1,
											"msg": "发送失败"
										});
									}
								});
							},
							error: function(httpResponse) {
								res.send({
									"code": 1,
									"msg": "发送失败"
								});
							}
						});
					},
					error: function(error) {
						res.send({
							"code": 1,
							"msg": "请求失败"
						});
					}
				})
			});
		},
		error: function(error) {
			res.send({
				"code": 1,
				"msg": "失败"
			});
		}
	});
}


/*
 * 设置成为普通口袋恋人
 */
function setPocket(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var objectId = req.body.objectId;
	var recommendUserQuery = new AV.Query(models.MLUser);
	recommendUserQuery.get(objectId, {
		success: function(user) {
			user.set("type", constant.USER_TYPE_PROFESSIONAL);
			user.save().then(function(user) {
				var tokenQuery = new AV.Query(models.HXToken);
				tokenQuery.descending("createdAt");

				tokenQuery.find({
					success: function(results) {
						var token = results[0].get('token');
						// 发送会话消息
						AV.Cloud.httpRequest({
							method: 'POST',
							url: 'https://a1.easemob.com/xiaocan/' + constant.APP_NAME + '/messages',
							headers: {
								"Content-Type": "application/json",
								"Authorization": "Bearer " + token
							},
							body: {
								"target_type": "users", // users 给用户发消息, chatgroups 给群发消息
								"target": [user.id], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,   
								// 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时  
								// 数组元素是groupid
								"msg": {
									"type": "cmd",
									"action": constant.ACTION_RESET_USER
								},
								"from": "MLSYSTEM", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的                
							},
							success: function(httpResponse) {
								AV.Cloud.run('sendSysMsg', {
									"touserId": user.id,
									"msg": "你的恋人故事已经撤下，你的身份将暂时变为普通口袋恋人，详情可通过意见反馈了解。"
								}, {
									success: function(result) {
										res.send({
											"code": 0,
											"msg": "发送成功"
										});
									},
									error: function(error) {
										res.send({
											"code": 1,
											"msg": "发送失败"
										});
									}
								});
							},
							error: function(httpResponse) {
								res.send({
									"code": 1,
									"msg": "发送失败"
								});
							}
						});
					},
					error: function(error) {
						res.send({
							"code": 1,
							"msg": "请求失败"
						});
					}
				})
			});
		},
		error: function(error) {
			res.send({
				"code": 1,
				"msg": "失败"
			});
		}
	});
}

function findRecmmandUser(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var objectId = parseInt(req.body.objectId);
	// 编辑专题
	var query = new AV.Query(models.MLUser);
	query.equalTo("molianId", objectId)
	query.find({
		success: function(users) {
			if (users.length != 0) {
				var data = {
					"username": req.session.username,
					"userId": users[0].id,
					"name": users[0].get("nickname")
				}
				res.send({
					"code": 0,
					"data": data
				})
			} else {
				res.send({
					"code": 1,
					"msg": "查找失败a"
				});
			}


		},
		error: function(error) {
			res.send({
				"code": 1,
				"msg": "查找失败"
			});
		}
	});
}

function realAuthentic(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var userId = req.body.userId;
	var type = parseInt(req.body.type);
	var MLUser = models.MLUser;
	var user = new MLUser();
	user.set("objectId", userId);
	user.set("realAuthentic", type);
	user.save(null, {
		success: function(user) {
			res.send({
				"code": 0,
				"msg": "成功"
			});
		},
		error: function(user, error) {
			console.log(error)
			res.send({
				"code": 1,
				"msg": "失败"
			});
		}
	});
}

exports.getPocketUser = getPocketUser;
exports.getUser = getUser;
exports.getUserAdd = getUserAdd;
exports.userAdd = userAdd;
exports.getUserEdit = getUserEdit;
exports.userEdit = userEdit;
exports.deleteRecmmandUser = deleteRecmmandUser;
exports.findRecmmandUser = findRecmmandUser;
exports.setEdit = setEdit;
exports.setPocket = setPocket;
exports.realAuthentic = realAuthentic;